//
//  HDRegisterViewController.swift
//  HuaDaoPeifu
//
//  Created by Erickson on 16/4/7.
//  Copyright © 2016年 paiyipai. All rights reserved.
//

import UIKit
import SVProgressHUD

enum RegType {
    case register , resetPwd,resChangePhone
}


class HDRegisterViewController: UIViewController ,UITextFieldDelegate{
    
    let phone = HDIconTextFieldView()
    let authCode = HDIconTextFieldView()
    var regType:RegType?
    var progressAlert = HDProgressAlert()
    //passType  0:是从个人中心传进来的，rightBarButton显示“登录”；1:是从登录进来的，rightBarButton不显示“登录”
    var passType:Int?
    //在登录页点击注册跳到哪里：0表示pop到上一页(个人中心需求)，1表示push到注册页(首页登录需求)
    var BackToWhere: Int?
    //在注册页点击登陆跳到哪里：0表示pop到上一页(首页需求)，1表示push到登录页(个人中心需求)
    var logBtnBackToWhere: Int?

    init(regType: RegType) {
        super.init(nibName: nil, bundle: nil)
        self.regType = regType
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    var countdownTimer: Timer?

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor(hex: 0xf8f8f8)
        title = (self.regType! == .register ? "注册" : (self.regType == .resChangePhone ? "绑定手机号":"忘记密码"))
        setupViews()
        naviBar()
        
        phone.textField.delegate = self
        authCode.textField.delegate = self
        phone.textField.clearButtonMode = .whileEditing
        phone.textField.keyboardType = UIKeyboardType.numberPad
        authCode.textField.keyboardType = .numberPad
        phone.textField.addTarget(self, action: #selector(getCodeButtonChange(_:)), for: .editingChanged)
    }
    
    func getCodeButtonChange (_ sender: UITextField) {
        if phone.textField.text?.characters.isEmpty == true {
            authCode.getCodeButton.setTitleColor(UIColor(hex:0x999999), for: UIControlState())
        }else {
            if isCounting {
                return
            }
            authCode.getCodeButton.setTitleColor(ConstantColor.appThemeColor, for: UIControlState())
        }
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        phone.textField.resignFirstResponder()
        authCode.textField.resignFirstResponder()
    }
    
    func naviBar() {
        if self.regType == RegType.register {
            navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: .plain, target: self, action: #selector(HDRegisterViewController.enterLogin))
            
            let guideRegister = UserDefaults.standard.bool(forKey: "GuideRegister")
            if guideRegister {
                navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "back"), style: .plain, target: self, action: #selector(backToGuide))
                
            }
        }
        else {

        }
    }
    //返回引导页
    func backToGuide() {
        phone.textField.resignFirstResponder()
        authCode.textField.resignFirstResponder()
       let backGuide = GuideViewController()
        UIApplication.shared.keyWindow?.rootViewController = backGuide;
        backGuide.scrollView.contentOffset.x = AppConstant.screenWidth*4
        backGuide.scrollView.isScrollEnabled = false
        self.dismiss(animated: true, completion: nil)
        UserDefaults.standard.set(false, forKey: "GuideRegister")
    }
    
    //MARK: setupView
    func setupViews() {
        phone.icon.image = UIImage(named: "phone")
        phone.textField.placeholder = RegErrorStatus.editPhone
        self.view.addSubview(phone)
        phone.snp.makeConstraints { (make) in
            make.top.equalTo(45)
            make.left.equalTo(self.view).offset(-1)
            make.right.equalTo(self.view).offset(1)
            make.height.equalTo(49)
        }
        
        authCode.icon.image = UIImage(named: "验证码")
        authCode.textField.placeholder = RegErrorStatus.editCode
        authCode.getCodeButton.isHidden = false
        authCode.getCodeButton.addTarget(self, action: #selector(HDRegisterViewController.getCode), for: .touchUpInside)
        self.view.addSubview(authCode)
        authCode.snp.makeConstraints { (make) in
            make.top.equalTo(phone.snp.bottom).offset(10)
            make.left.equalTo(self.view).offset(-1)
            make.right.equalTo(self.view).offset(1)
            make.height.equalTo(49)
        }
        
        let nextBtn = HDNextStepButton(title:"下一步")
        view.addSubview(nextBtn)
        nextBtn.snp.makeConstraints { (make) in
            make.top.equalTo(authCode.snp.bottom).offset(50)
            make.left.equalTo(view).offset(37)
            make.right.equalTo(view).offset(-37)
            make.height.equalTo(40)
        }
        nextBtn.addTarget(self, action: #selector(HDRegisterViewController.nextStep), for: .touchUpInside)
        
        if self.regType == .register {
            let regPro = UINib(nibName: "HDRegPromptView", bundle: nil).instantiate(withOwner: self, options: nil).last as! HDRegPromptView
            view.addSubview(regPro)
            regPro.delegate = self
            regPro.snp.makeConstraints { (make) in
                make.top.equalTo(nextBtn.snp.bottom).offset(10)
                make.centerX.equalTo(view)
                make.width.equalTo(240)
                make.height.equalTo(20)
            }
        }
    }
    
    //MARK: 点击下一步，验证码认证
    func nextStep() {
        
        phone.textField.resignFirstResponder()
        authCode.textField.resignFirstResponder()
        
        if phone.textField.text == nil || phone.textField.text == "" {
            progressAlert.pleaseEnterPhoneNumber()
            return
        }
        if authCode.textField.text == nil || authCode.textField.text == "" {
            progressAlert.pleaseEnterAuthCode()
            return
        }
        var reqmode:String = "1"
        if self.regType == .resChangePhone {
            reqmode = "3"
        }
        
        let ckAuthCode = PYPCkauthcode(phone: phone.textField.text, code:authCode.textField.text, reqmode:reqmode)
        
        HDApiManagerHandler.requestCkauthcode(ckAuthCode, success: { (dict) in
            
            if dict["status"]?.int32Value == 1 {
                if self.regType == .resChangePhone {
                    var phoneModel = HDUpdatePhone()
                    phoneModel.newphone = self.phone.textField.text!
                    phoneModel.code = self.authCode.textField.text!
                    phoneModel.atk = HDAccountHandler.token!
                    
                    HDApiManagerHandler.requestUpdatePhone(phoneModel, success: { (response) in
                        if response["status"]?.int32Value == 1 {
                            let contr = HDChangePhoneSuccessViewController()
                            contr.phoneNumber = self.phone.textField.text!
                            self.navigationController?.pushViewController(contr, animated: true)
                        }else{
                            SVProgressHUD.showError(response["msg"] as! String)
                        }
                        }, failure: { (failure) in
                            
                    })
                    
                    return
                }else{
                    var regStr = PYPReg()
                    regStr.phone = ckAuthCode.phone
                    regStr.code = ckAuthCode.code
                    let pwd = HDPasswordViewController(setType: .set)
                    pwd.regStr = regStr
                    self.navigationController?.pushViewController(pwd, animated: true)
                    return
                }
                
            }
            let msg = dict["msg"] as! String
            SVProgressHUD.showError(msg)
            
        }) { (error) in
            
        }
    }
    
    func enterLogin() {
        let loginVC = HDLoginViewController()
        if logBtnBackToWhere == 1 {
            loginVC.registerBtnBackToWhere = BackToWhere
            navigationController?.popViewController(animated: true)
        }else {
            loginVC.registerBtnBackToWhere = BackToWhere
            navigationController?.pushViewController(loginVC, animated: true)
        }
        
    }
    //倒计时
    var remainingSeconds: Int = 0 {
        willSet {
            authCode.getCodeButton.setTitle("(\(newValue)秒)", for: UIControlState())
            if newValue <= 0 {
                authCode.getCodeButton.setTitle("重新获取", for: UIControlState())
                isCounting = false
            }
        }
    }
    var isCounting = false {
        willSet {
            if newValue {
                countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
                remainingSeconds = 60
                authCode.getCodeButton.setTitleColor(UIColor(hex:0x999999), for: UIControlState())
            } else {
                countdownTimer?.invalidate()
                countdownTimer = nil
                authCode.getCodeButton.setTitleColor(ConstantColor.appThemeColor, for: UIControlState())
            }
            authCode.getCodeButton.isEnabled = !newValue
        }
    }
    func updateTime(_ timer: Timer) {
        remainingSeconds -= 1
    }
    
    func getCode() {
        if phone.textField.text == nil || phone.textField.text == "" {
            progressAlert.pleaseEnterPhoneNumber()
            return
        }
        if phone.textField.text!.characters.count != 11 {
            progressAlert.pleaseEnterRightPhoneNumber()
            return
        }
        
        var reqmode:String = "1"
        if self.regType == .resChangePhone {
            reqmode = "3"
        }
        let authCode = PYPAuthcode(phone: phone.textField.text!, tms: "0", reqmode: reqmode)
        HDApiManagerHandler.requestAuthcode(authCode, success: {dict in
            if dict["status"]?.int32Value == 1 {
                
        self.authCode.startTimer()
//                #if DEBUG
//                    let code = dict["data"] as! NSDictionary
//                    let codeString = code["code"] as! NSNumber
//                    self.authCode.textField.text = String(codeString.intValue)
//                    
//                    print(codeString.intValue)
                
                
//                #endif
                self.isCounting = true
                return
            }
            let msg = dict["msg"] as? String
            print("======\(String(describing: msg))")
            SVProgressHUD.showError(msg)
            
        }) { (error) in
            
        }
    }
    
}

extension HDRegisterViewController : HDRegPromptViewDelegate {
    func didSelectedAgreement() {
        navigationController?.pushViewController(HDUserAgreementViewController(), animated: true)
    }
}

protocol HDRegPromptViewDelegate :class {
    func didSelectedAgreement()
}
class HDRegPromptView: UIView {
    
    weak var delegate:HDRegPromptViewDelegate?
    @IBAction func enterAgreement(_ sender: AnyObject) {
        delegate?.didSelectedAgreement()
    }
    
}



